// basic file operations
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char** argv) {
// Definitions
	
	bool finished=false;
	int xmax,ymax;
	int xp,yp;
	string buffer;
	int x,y,x2,y2;
	int xc,yc;
	char string[50];
	char *temp1;
	double temp;
	ifstream infile,infile2;

	xmax=640;
	ymax=480;
	xp=16;
	yp=16;
	double* tab=NULL;
	tab = new double[(xmax/xp)*(ymax/yp)];


	cout<<"file to open"<<endl;
	cin>>string;
	infile2.open(string);

	cout<<"file to write"<<endl;
	cin>>string;
	ofstream outfile(string);

	for(int i=1;i<argc;i++){

		infile.open(argv[i],ios::binary);
	
		infile2>>xc;
		infile2>>yc;
	
		for(int i=0;i<(xmax/xp)*(ymax/yp);i++){
			tab[i]=0;
		}

// Parse headers	
		getline(infile,buffer);
		if(buffer[0] != 'P'){
			cout<<"Error"<<endl;
			return 1;
		}

		getline(infile,buffer);
		if(buffer[0] == '#'){
			cout<<"Error"<<endl;
			return 1;
		}

		getline(infile,buffer);
		if(buffer[0] == '#'){
			cout<<"Error"<<endl;
			return 1;
		}

//start normalize
		temp=0;
		temp1=new char();		
		for(y=0;y<ymax;y++){
			for(x=0;x<xmax;x++){
				temp=0;
				temp+=(unsigned int)infile.get()*255*255;
				temp+=(unsigned int)infile.get()*255;
				temp+=(unsigned int)infile.get();
				tab[y/yp*(xmax/xp)+x/xp]+=temp/(double)(255*255*255+255*255+255);
				if(infile.eof()){
					cout<<x<<"\n"<<y<<endl;
					break;
				}

			}
				if(infile.eof())break;
		}

		for(y=0;y<ymax/yp;y++){
			for(x=0;x<xmax/xp;x++){
				outfile<<tab[y*(xmax/xp)+x]/(xp*yp)<<"\t";
			}
		}
		outfile<<(double)xc/(double)xmax<<"\t"<<(double)yc/(double)ymax<<"\n";
		infile.close();
	}
	delete [] tab;
	tab=NULL;
	outfile<<'.';
	outfile.close();
}
